//  通用，零散 工具方法

// 判断是否是 url
export const isURL = (s) => /^http[s]?:\/\/.*/.test(s);

// localstorage 保存数据
export const saveLocal = (key,val) => {
  const t = typeof val;
  if(t === 'object'){
    localStorage.setItem(key,JSON.stringify(val))
  }else{
    localStorage.setItem(key,val)
  }
}

// 获取 localstorage 保存的数据 type 可以用来对数据做初步类型转换 目前仅支持 json对象转换
export const getLocal = (key,type) => {
  const r = localStorage.getItem(key) || undefined;
  if(type == 'object' && r){
    return JSON.parse(r)
  }
  return r;
}

// 清空 localstorage
export const clearLocal = () => {
  localStorage.clear()
}


// 对象深度克隆
export const clone = (obj = {}) => {
  const f = (o) => {
    const t = Array.isArray(o)?'array':typeof o;
    const r = t == 'array' ? [] : {};
    if(t == 'array'){
      o.forEach(v => {
        if(typeof v == 'object'){
          r.push(f(v))
        }else{
          r.push(v)
        }
      })
    }
    else if(t == 'object'){
      Object.keys(o).forEach(k => {
        const v = o[k]
        if(typeof v == 'object'){
          r[k] = f(v);
        }else{
          r[k] = v
        }
      })
    }
    //
    return r;
  }
  
  return f(obj);
}

// 对象深度合并
export const combine = (m = {},n = {}) => {
  //
  const res = clone(m);
  const has = Object.prototype.hasOwnProperty;

  const f = (r,s) => {
    const is = typeof r == typeof s && typeof r == 'object'
    if(!is) return s;
    const t = Array.isArray(r) ? 'array' : 'object'
    //
    if(t == 'array'){
      return [...r,...s]
    }else{
      Object.keys(s).forEach(k => {
        const b = has.call(r,k);
        const v = s[k]
        if(!b){
          r[k] = v;
        }else{
          r[k] = f(r[k],v)
        }
      })
      return r;
    }
  }
  //
  return f(res,n);
}